<template>
  <div>
    <div class="flex items-center cursor-pointer" @click="handleGo">
      <el-icon>
        <ArrowLeftBold />
      </el-icon>
      <span class="pl-5">{{ $t("修改卡片") }}</span>
    </div>
    <div class="mt-6 cardStats">
      <h3 class="text-lg">{{ $t("卡片属性") }}</h3>
      <el-card class="mt-5">
        <el-row>
          <el-col :span="12">
            <el-descriptions :column="1">
              <el-descriptions-item :label="$t('卡片类型')">{{
                state.category_name
              }}</el-descriptions-item>
              <!-- <el-descriptions-item :label="$t('扣款方式')">
                <span v-if="state.asset_type === 'balance'">{{
                  $t("余额")
                }}</span>
                <span v-if="state.asset_type === 'credit'">{{
                  $t("授信")
                }}</span>
                <span v-if="state.asset_type === 'coin'">{{
                  $t("虚拟币")
                }}</span>
              </el-descriptions-item>-->
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div class="mt-6" v-loading="loading">
      <h3 class="text-lg">{{ $t("基本属性") }}</h3>
      <el-card class="mt-5">
        <el-form
          ref="createFormRef"
          label-position="top"
          :model="state.cardInfo"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('卡片额度')" prop="total_amount">
                <div style="display: inline-block; width: 80%">
                  <el-input
                    v-model="state.cardInfo.total_amount"
                    size="large"
                    :placeholder="$t('请输入额度')"
                    disabled
                    type="number"
                  ></el-input>
                </div>
                <el-select
                  v-model="state.cardInfo.currency"
                  :placeholder="$t('币种')"
                  class="inline-block"
                  size="large"
                  disabled
                  style="display: inline-block; width: 20%"
                >
                  <el-option
                    v-for="item in state.cardsCurrencyList"
                    :key="item.currency"
                    :label="item.currency"
                    :value="item.currency"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item :label="$t('卡片别名')" prop="nick_name">
                <el-input
                  v-model="state.cardInfo.nick_name"
                  size="large"
                  :placeholder="$t('请输入卡别名')"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('姓氏')" prop="last_name">
                <el-input
                  v-model="state.cardInfo.last_name"
                  size="large"
                  :placeholder="$t('请输入姓氏')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('名字')" prop="first_name">
                <el-input
                  v-model="state.cardInfo.first_name"
                  size="large"
                  :placeholder="$t('请输入名字')"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('手机号')" prop="mobile_number">
                <el-input
                  v-model="state.cardInfo.area_code"
                  :placeholder="$t('区号')"
                  class="inline-block"
                  style="width: 80px"
                  size="large"
                  type="number"
                >
                </el-input>
                <div class="inline-block" style="width: calc(100% - 80px)">
                  <el-input
                    v-model="state.cardInfo.mobile_number"
                    :placeholder="$t('输入手机号码')"
                    class="input-with-select"
                    size="large"
                    style="width: 100%"
                    type="number"
                  >
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('邮箱')" prop="email">
                <el-input
                  v-model="state.cardInfo.email"
                  size="large"
                  :placeholder="$t('请输入邮箱地址')"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <div class="flex items-center justify-center">
      <el-button size="large" type="danger" class="mt-10" @click="save">{{
        $t("保存")
      }}</el-button>
    </div>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { GetCardsDetail, EditCard, GetCardsCurrency } from "@/api/card";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const handleGo = () => {
  router.push({
    path: "/card/management",
  });
  localStorage.setItem("cardId", route.query.card_id);
};

const loading = ref(false);

const state = reactive({
  category_name: "",
  asset_type: "",
  cardInfo: {
    total_amount: "",
    nick_name: "",
    area_code: "",
    last_name: "",
    first_name: "",
    mobile_number: "",
    email: "",
  },
});

const checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("邮箱不能为空"));
  } else {
    const emailRegExp =
      /^([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/;
    if (emailRegExp.test(value)) {
      callback();
    } else {
      return callback(new Error("请输入正确的邮箱"));
    }
  }
};

const checkTotalAmount = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t("卡片额度不能为空")));
  } else {
    if (value <= 1) {
      return callback(new Error(`t("卡片额度必须大于1")`));
    } else if (value > Number(state.amountInfo.amount)) {
      return callback(
        new Error(`${t("卡片额度必须小于")}${state.amountInfo.amount}`)
      );
    } else {
      callback();
    }
  }
};

const rules = reactive({
  total_amount: [
    { required: true, message: t("请输入卡片额度"), trigger: "blur" },
    { validator: checkTotalAmount, trigger: "blur" },
  ],
  nick_name: [
    { required: true, message: t("请输入卡片别名"), trigger: "blur" },
  ],
  last_name: [{ required: true, message: t("请输入姓氏"), trigger: "change" }],
  first_name: [{ required: true, message: t("请输入名字"), trigger: "change" }],
  mobile_number: [
    { required: true, message: t("请输入手机号"), trigger: "blur" },
    { min: 5, max: 16, message: t("请输入6-16位的数字"), trigger: "blur" },
  ],
  email: [
    { required: true, message: t("请输入邮箱"), trigger: "blur" },
    { validator: checkEmail, trigger: "blur" },
  ],
});

// 修改保存
const save = async () => {
  let query = { ...state.cardInfo };
  query.mobile = query.mobile_number;
  query.card_id = route.query.card_id;
  delete query["mobile_number"];
  try {
    loading.value = true;
    await EditCard(query);
    loading.value = false;
    ElMessage.success(t("修改成功"));
    router.replace(`/card/management`);
  } catch {
    loading.value = false;
  }
};

// 获取详情回显
const getCardsDetail = async () => {
  try {
    loading.value = true;
    const data = (await GetCardsDetail({ card_id: route.query.card_id })) || {};
    loading.value = false;
    state.asset_type = data.asset_type || "";
    state.category_name = data.category_name || "";
    const primary_contact = data.primary_contact || {};
    for (const item in primary_contact) {
      state.cardInfo[item] = primary_contact[item];
    }
    state.cardInfo.nick_name = data.nick_name || "";
    state.cardInfo.total_amount = data.total_amount || 0;
    state.cardInfo.currency = data.currency || "";
  } catch {
    loading.value = false;
  }
};

const getCardsCurrency = async () => {
  try {
    const { cards_currency } = await GetCardsCurrency({
      category_id: state.cardInfo.category_id,
    });
    state.cardsCurrencyList = cards_currency;
    state.cardInfo.currency = state.cardsCurrencyList[0].currency;
  } catch {}
};
onMounted(async () => {
  await getCardsCurrency();
  await getCardsDetail();
});
</script>
<style lang="scss" scoped>
.input-prefix {
  color: #707276; /* 输入框前缀的颜色 */
  font-size: 14px; /* 输入框前缀的字体大小 */
  line-height: 1.5715; /* 与输入框的行高一致 */
  vertical-align: middle;
}
</style>
